/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import java.util.List;
import java.util.Set;
import models.Category;
import models.Course;
import models.User;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Aster
 */
public class CategoryDao {

    private final Session session;

    public CategoryDao(Session session) {
        this.session = session;
    }

    public List<Category> findAll() {
        Transaction tx = session.beginTransaction();
        List<Category> list = session.createQuery("from Category").list();
        tx.commit();
        return list;
    }

    public void save(Category category) {
        Transaction tx = session.beginTransaction();
        session.save(category);
        tx.commit();
    }

    public void update(Category category) {
        Transaction tx = session.beginTransaction();
        session.update(category);
        tx.commit();
    }

    public Category get(String id) {
        return (Category) session.get(Category.class, id);
    }

    public void delete(Category category) {
        Transaction tx = session.beginTransaction();
        try {
            Set<Course> all = category.getCourses();
            System.out.println("WAAA");
            for(Course course : all){
                
                Set<User> alluser = course.getUsers();
                for(User user: alluser){
                    System.out.println(user.getAddress());
                    user.getCourses().remove(course);
                }
                course.getUsers().clear();
                session.delete(course);
                //session.delete(course);
            }            
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("WAT IS NUL?");
        }
        session.delete(category);
        tx.commit();
    }
}
